package com.uetoken.cn.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.sulink.numberkeyboard.popWindow.BasePayPop;
import com.sulink.numberkeyboard.popWindow.SimplePayPopWindow;
import com.uetoken.cn.R;
import com.uetoken.cn.adapter.holder.FundInfoHolder;
import com.uetoken.cn.adapter.holder.UserTransferHolder;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.bean.CheckUserInfoBean;
import com.uetoken.cn.bean.MsgBean;
import com.uetoken.cn.common.ApiHelper;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.network.OkHttpUtils;
import com.uetoken.cn.network.Params;
import com.uetoken.cn.network.WebResponse;
import com.uetoken.cn.view.DialogHelper;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 出货
 */
public class ShipmentNewActivity extends BaseActivity implements UserTransferHolder.OnSingleTransferClickListener, WebResponse {

    private static final String TAG = "ShipmentNewActivity==";
    @BindView(R.id.topbar)
    QMUITopBar mTopbar;
    @BindView(R.id.rootFundInfoLayout)
    FrameLayout mRootFundInfoLayout;
    @BindView(R.id.rootShipmentLayout)
    FrameLayout mRootShipmentLayout;
    @BindView(R.id.verifyBindBtn)
    Button mVerifyBindBtn;

    @BindView(R.id.annotationTv)
    TextView annotationTv;
    @BindView(R.id.detailsTv)
    TextView detailsTv;
    @BindView(R.id.detailsLayout)
    RelativeLayout detailsLayout;
    @BindView(R.id.shipmentLayout)
    RelativeLayout shipmentLayout;
    @BindView(R.id.notShipmentScrollView)
    ScrollView notShipmentScrollView;
    /**
     * 钱包转账账号校验网络请求码
     */
    public static final int NETWORK_REQUEST_USER_INFO = 10;
    /**
     * 钱包转账账号校验网络请求码
     */
    public static final int NETWORK_REQUEST_STOCK_OUT = 11;
    /**
     * 钱包出货支付密码返回码
     */
    private static final int INTENT_REQUEST_PWD_RETURN_CODE = 12;
    /**
     * 钱包id
     */
    private String purseId;
    /**
     * 钱包名字
     */
    private String purseName;
    /**
     * 钱包余额
     */
    private String balance;
    /**
     * 钱包冻结
     */
    private String freeze;
    private boolean isCheck = false;

    private FundInfoHolder mFundInfoHolder;
    private UserTransferHolder mUserTransferHolder;
    private View mView1;
    private View mView2;
    private String userAccount;
    private String tonodeId;
    private String amount;
    private String pwd;
    private String pursepic;
    private String pagestockout;


    @Override
    public int getLayoutId() {
        return R.layout.activity_shipment_new;
    }

    @Override
    public void initView() {
// 沉浸式状态栏
        QMUIStatusBarHelper.translucent(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            QMUIStatusBarHelper.setStatusBarLightMode(this);
        }
        ButterKnife.bind(this);
        initTopBar();
        if (mFundInfoHolder == null) {
            mView1 = LayoutInflater.from(this).inflate(R.layout.item_fund_info, null);
            mFundInfoHolder = new FundInfoHolder(mView1);
            mView1.setTag(mFundInfoHolder);
        } else {
            mFundInfoHolder = (FundInfoHolder) mView1.getTag();
        }
        mRootFundInfoLayout.addView(mView1);

        if (mUserTransferHolder == null) {
            mView2 = LayoutInflater.from(this).inflate(R.layout.item_solo_transfer_context, null);
            mUserTransferHolder = new UserTransferHolder(mView2);
            mView2.setTag(mUserTransferHolder);
        } else {
            mUserTransferHolder = (UserTransferHolder) mView2.getTag();
        }
        mUserTransferHolder.setOnSingleTransferClickListener(this);
        mRootShipmentLayout.addView(mView2);
        mVerifyBindBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
        mVerifyBindBtn.setClickable(false);
        initTextChangedListener();
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        purseId = intent.getStringExtra("purseId");
        purseName = intent.getStringExtra("purseName");
        balance = intent.getStringExtra("balance");
        freeze = intent.getStringExtra("freeze");
        pagestockout = intent.getStringExtra("pagestockout");
        pursepic = intent.getStringExtra("pursepic");
        if (mFundInfoHolder != null) {
            String walletName = purseName + getResources().getString(R.string.tabbar_property_txt)
                    + "(" + purseName + getResources().getString(R.string.str_inventory) + ")";
            mFundInfoHolder.mWalletNameTv.setText(walletName);
            mFundInfoHolder.mAmountTv.setText(balance);
            String freezeLimit = getResources().getString(R.string.str_freeze) + " " + freeze;
            mFundInfoHolder.mFreezeLimitTv.setText(freezeLimit);
        }

        if (mUserTransferHolder != null) {
            mUserTransferHolder.mAvailableBalanceValTv.setText(balance);
        }

        detailsTv.setText(pagestockout.replace("\\n", "\n"));
    }

    @Override
    public void init() {

    }

    public void initTextChangedListener() {
        //InputType.TYPE_NUMBER_FLAG_DECIMAL //小数点型
        //InputType.TYPE_CLASS_NUMBER //整数型
        //设置Input的类型两种都要
        if (mUserTransferHolder != null) {
//            mUserTransferHolder.mAmountEnteredEt.setInputType(InputType.TYPE_CLASS_NUMBER);
            mUserTransferHolder.mAmountEnteredEt.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
            //设置字符过滤
            mUserTransferHolder.mAmountEnteredEt.setFilters(new InputFilter[]{new InputFilter() {

                @Override
                public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                    if (source.equals(".") && dest.toString().length() == 0) {
                        return "0.";
                    }
                    if (dest.toString().contains(".")) {
                        int index = dest.toString().indexOf(".");
                        int length = dest.toString().substring(index).length();
                        if (length == 3) {
                            return "";
                        }
                    }
                    return null;
                }
            }});

            //账号输入框
            mUserTransferHolder.mAccountEt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    //输入文本之前的状态
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //输入文字中的状态，count是一次性输入字符数
                    if (s.length() > 0) {
                        mUserTransferHolder.mVerifyBtn.setBackgroundResource(R.color.app_color_common_yellow);
                        mUserTransferHolder.mVerifyBtn.setClickable(true);
                    } else {
                        mUserTransferHolder.mVerifyBtn.setBackgroundResource(R.color.app_color_common_gray);
                        mUserTransferHolder.mVerifyBtn.setClickable(false);
                    }
                    if ((mUserTransferHolder.mAmountEnteredEt.getText() + "").length() > 0 && s.length() > 0) {
                        mVerifyBindBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
                        mVerifyBindBtn.setClickable(true);
                    } else {
                        mVerifyBindBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                        mVerifyBindBtn.setClickable(false);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                    //输入文字后的状态
                }
            });
            //转账金额输入框
            mUserTransferHolder.mAmountEnteredEt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    //输入文本之前的状态
                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //输入文字中的状态，count是一次性输入字符数
                    if (s.length() > 0) {
                        mUserTransferHolder.mDelIv.setVisibility(View.VISIBLE);
                    } else {
                        mUserTransferHolder.mDelIv.setVisibility(View.GONE);
                    }
                    if ((mUserTransferHolder.mAccountEt.getText() + "").length() > 0 && s.length() > 0) {
                        mVerifyBindBtn.setBackgroundResource(R.drawable.yellow_circular_bead_shape);
                        mVerifyBindBtn.setClickable(true);
                    } else {
                        mVerifyBindBtn.setBackgroundResource(R.drawable.gray_circular_bead_shape);
                        mVerifyBindBtn.setClickable(false);
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
                    //输入文字后的状态
                }
            });
        }
    }

    private void initTopBar() {
        mTopbar.setTitle(R.string.str_shipment_btn);
        mTopbar.addLeftImageButton(R.drawable.ic_back, R.id.qmui_topbar_item_left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void clickCheckAccount() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getUserBaseInfoUrl(), NETWORK_REQUEST_USER_INFO,
                Params.getUserInfoParams(userAccount, "0"));
    }

    private void purseStockOut() {
        showLoading();
        OkHttpUtils.getInstance().getStringWithParam(this, ApiHelper.getStockoutUrl(), NETWORK_REQUEST_STOCK_OUT,
                Params.getStockoutParams(purseId, tonodeId, amount, pwd));
    }

    @Override
    public void onCheckAccountClick(View view) {
        if (mUserTransferHolder != null) {
            userAccount = mUserTransferHolder.mAccountEt.getText() + "";
        }
        if ("".equals(userAccount) || userAccount == null || "null".equals(userAccount)) {
            ToastUtils.showShort(R.string.toast_account_can_not_empty);
            return;
        }
        clickCheckAccount();
    }

    @Override
    public void onDeleteAmountClick(View view) {
        if (mUserTransferHolder != null) {
            mUserTransferHolder.mAmountEnteredEt.setText("");
        }
    }

    @Override
    public void onFullAmountClick(View view) {
        if (mUserTransferHolder != null) {
            mUserTransferHolder.mAmountEnteredEt.setText(balance);
        }
    }

    @Override
    public void onSuccessResponse(Call call, String response, int requestCode) throws IOException {
        LogUtils.dTag(TAG, "onSuccessResponse== response = " + response);
        dissmissDialog();
        switch (requestCode) {
            case NETWORK_REQUEST_USER_INFO:
                CheckUserInfoBean mCheckUserInfoBean = new Gson().fromJson(response, CheckUserInfoBean.class);
                if (mCheckUserInfoBean.getResult() > 0) {
                    CheckUserInfoBean.DataBean mCheckUserInfoDataBean = mCheckUserInfoBean.getData();
                    isCheck = true;
                    tonodeId = mCheckUserInfoDataBean.getNodeid() + "";
                    if (mUserTransferHolder != null) {
                        mUserTransferHolder.mAccountInfoLayout.setVisibility(View.VISIBLE);
                        mUserTransferHolder.mUserNameTv.setText(mCheckUserInfoDataBean.getNodename());
                        mUserTransferHolder.mUserPhoneNumberTv.setText(mCheckUserInfoDataBean.getMobileno());
                    }
                } else {
                    isCheck = false;
                    if (mUserTransferHolder != null) {
                        mUserTransferHolder.mAccountInfoLayout.setVisibility(View.GONE);
                    }
                    ToastUtils.showShort(mCheckUserInfoBean.getMessage());
                }
                break;
            case NETWORK_REQUEST_STOCK_OUT:
                //{"result":-1,"message":"转入方不存在"}
                MsgBean mMsgBean = new Gson().fromJson(response, MsgBean.class);
                ToastUtils.showShort(mMsgBean.getMessage());
                if (mMsgBean.getResult() > 0) {
                    finish();
                }
                break;
        }
    }

    @Override
    public void onFailResponse(Call call, IOException e, int requestCode) {
        dissmissDialog();
    }

    private void reconfirmDialog() {
        boolean isPayPwd = SPUtils.getInstance(Constant.UE_TOKEN_PREFERENCE_USER_INFO).getBoolean(Constant.IS_PAY_PWD, true);
        if (isPayPwd) {
            //没有支付密码
            new QMUIDialog.MessageDialogBuilder(this)
                    .setTitle(getResources().getString(R.string.str_not_setting_pay_pwd))
                    .setMessage(getResources().getString(R.string.str_you_not_setting_pay_pwd_not_user))
                    .addAction(getResources().getString(R.string.str_later), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction(getResources().getString(R.string.str_right_now_setting), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            Intent settingPayPwdIntent = new Intent(ShipmentNewActivity.this, ForgetPasswordActivity.class);
                            settingPayPwdIntent.putExtra("pwd", "pay");
                            startActivity(settingPayPwdIntent);

                        }
                    }).show();
        } else {
            if (mUserTransferHolder != null) {
                userAccount = mUserTransferHolder.mAccountEt.getText() + "";
                amount = mUserTransferHolder.mAmountEnteredEt.getText() + "";
            } else {
                userAccount = "null";
                amount = "0";
            }
            DialogHelper.showMessageDialog(this, getResources().getString(R.string.str_reconfirm_title_dialog),
                    Html.fromHtml(getResources().getString(R.string.str_stockout_msg_dialog, amount + purseName,
                            userAccount + getResources().getString(R.string.str_account_number))),
                    getResources().getString(R.string.str_reconfirm_negative_dialog),
                    getResources().getString(R.string.str_reconfirm_positive_dialog), new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    }, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                            if (Double.parseDouble(amount) <= Double.parseDouble(balance)) {
                                SimplePayPopWindow popWindow = new SimplePayPopWindow(ShipmentNewActivity.this);
                                amount = String.format("%.2f", Double.parseDouble(amount));
                                popWindow.setTvPayValue(amount + purseName);//实际支付金额
//                                popWindow.setTvAmount("200CV");//支付总金额
//                                popWindow.setTvDeduction("抵扣100P币");//优惠金额
                                popWindow.setPayTypeImageUrl(pursepic);
                                popWindow.setTvPayType(purseName);
                                balance = String.format("%.2f", Double.parseDouble(balance));
                                popWindow.setTvBalance(balance);
                                popWindow.showAtLocation(mVerifyBindBtn, Gravity.BOTTOM, 0, 0);
                                popWindow.setOnPayListener(new BasePayPop.PayEnterPassWordListener() {
                                    @Override
                                    public void onCancel() {

                                    }

                                    @Override
                                    public void onInputFinished(String passWord) {
                                        pwd = EncodeUtils.base64Encode2String(passWord.getBytes());
                                        //支付密码输入完成
                                        purseStockOut();
//                                        Toast.makeText(MainActivity.this,"密码："+passWord,Toast.LENGTH_LONG).show();
                                    }
                                });

//                                Intent pwdIntent = new Intent(ShipmentNewActivity.this, PaymentPasswordActivity.class);
//                                pwdIntent.putExtra("amount", amount + purseName);
//                                pwdIntent.putExtra("subject", purseName + getResources().getString(R.string.transfer_accounts_txt));
//                                //密码输入界面需要显示的参数
//                                pwdIntent.putExtra("pursename", purseName);
//                                pwdIntent.putExtra("icon", pursepic);
//                                pwdIntent.putExtra("balance", balance);
//                                startActivityForResult(pwdIntent, INTENT_REQUEST_PWD_RETURN_CODE);
                            } else {
                                ToastUtils.showShort(getResources().getString(R.string.str_insufficient_balance));
                            }
                        }
                    });
        }
    }

    @OnClick(R.id.verifyBindBtn)
    public void onViewClicked() {
        if (!isCheck) {
            ToastUtils.showShort(R.string.str_please_check_account);
            return;
        }
        reconfirmDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == INTENT_REQUEST_PWD_RETURN_CODE && resultCode == RESULT_OK) {
            pwd = data.getStringExtra("inputFinish");
            //支付密码输入完成
            purseStockOut();
        }
    }
}
